package com.silverbox.sweeporder.service.webmsg.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.blibao.msg.ActiveMqttUtils;
import com.silverbox.core.result.CoreResponse;
import com.silverbox.core.result.CoreResponse.StatusInfo;
import com.silverbox.core.util.AlibabaMQTT;
import com.silverbox.core.util.Utils;
import com.silverbox.shopper.dubboApi.info.ShopperInfoServiceApi;
import com.silverbox.shopper.entity.DiningArea;
import com.silverbox.shopper.entity.ShopperConfig;
import com.silverbox.sweeporder.common.Constants;
import com.silverbox.sweeporder.controller.msg.vo.SendMsgEntryVO;
import com.silverbox.sweeporder.core.jpush.JpushUtil;
import com.silverbox.sweeporder.core.jpush.JpushUtil.PushType;
import com.silverbox.sweeporder.service.webmsg.WebMsgService;
import com.silverbox.waimai.dubboApi.order.WaimaiServiceApi;
import com.silverbox.waimai.entity.MsgRecord;
import com.silverbox.waimai.entity.Waimai;

@Component
public class WebMsgServiceImpl implements WebMsgService {

	private static Logger logger = LoggerFactory.getLogger(WebMsgServiceImpl.class);

	@Autowired
	private ShopperInfoServiceApi shopperInfoServiceApi;
	
	@Autowired
	private WaimaiServiceApi waimaiServiceApi;
	
	@Autowired
	private WebMsgService webMsgService;
	
	

	@Override
	public void sendWebMsg(Waimai order, Long machineId, int msgType, Integer aliyunMqtt, Long hostMachineId,String msgCode) {
		try {
			logger.info("消息推送：shopperId=" + order.getShopId() + ",orderNum=" + order.getOrderNum() + ",tableNum:"
					+ ",msgType=" + msgType + ",aliyunMqtt=" + aliyunMqtt + ",hostMachineId=" + hostMachineId);
			Map<String, Object> msgObj = new HashMap<String, Object>();
			Map<String, Object> msg = new HashMap<String, Object>();
			msgObj.put("from", order.getBuyerId());
			msgObj.put("to", order.getShopId() + "");
			msgObj.put("toUserType", "shopper");
			msgObj.put("sendType", "mass");
			if (new Integer(1).equals(order.getPayStatus())) {
				msg.put("totalFee", null == order.getTotalFee() ? 0.0 : order.getTotalFee());
			}
			// 小于2的都是扫码下单推送消息类型
			if (msgType < 2) {
				if (null != hostMachineId) {
					msgObj.put("machineId", hostMachineId + "");
				} else {
					msgObj.put("machineId", (machineId == null ? "" : (machineId + "")));
				}
				msg.put("tableNo", order.getTableNum());
				// 预下单
				if (new Integer(1).equals(order.getOrderType())) {
					msg.put("msg", (msgType == 1 ? "顾客已下单" : "顾客已付款"));
				} else {
					msg.put("msg", "桌号：" + order.getTableNum() + (msgType == 1 ? "，顾客已下单" : "，顾客已付款"));
				}
				// add by ywc 2019年12月5日 	先吃后付下单/加菜消息改为后端推送
				if (!Utils.isEmpty(order.getTableNum()) || !Utils.isEmpty(order.getTableUid())) {
					msg.put("msg",  "桌号："+order.getTableNum()+"，顾客已" + (order.getOrderStatus()==3?"加菜":"下单"));
				}
				msg.put("orderNum", order.getOrderNum());
				msg.put("tableUid", order.getTableUid() == null ? "" : order.getTableUid());
				if (msgType == 1) {// 顾客下单消息
					msg.put("orderType", 0);// 顾客下单类型标记是正常订单还是加菜订单
					msg.put("type", "order");
				} else if (msgType == -1) { // 预下单，扫桌台二维码就座
					msg.put("msg", "顾客：" + order.getBuyNick() + "已就座");
					msg.put("type", "sit");
					// 顾客就座时，需要给所有机器推送消息
					msgObj.put("machineId", "");
				} else {
					//获取店铺是否开启口碑正餐后付功能
					ShopperConfig config= shopperInfoServiceApi.getShopperConfig(order.getShopId(), "CTR_KOUBEI_DINNER");
					if (config != null && config.getPropValue() != null
							&& new Integer(1).equals(Integer.valueOf(config.getPropValue()))) {
						if(!Utils.isEmpty(order.getBuyerId())){
							msg.put("msg",  "顾客："+order.getBuyerId()+"，已付款");
						}else{
							msg.put("msg",  "顾客已付款");
						}
						msg.put("totalPay", order.getTotalPay());
						msg.put("orderNum", order.getOrderNum());
						msg.put("source",  order.getSource());//业务类型：正餐1 快餐0或者null
						msg.put("isOut",  order.getIsOut());//堂食：0外带：1 
						msg.put("hexiaoType",  order.getHexiaoType());//线上点：0扫码点：1 
						msg.put("payStatus",  order.getPayStatus());//后付：0先付：1 
						if(!Utils.isEmpty(order.getTableNum())){
							msg.put("tableNum",  order.getTableNum());
						}
						msg.put("type", "koubei-order-payNotify");
						logger.info("口碑后付支付消息msg============="+JSONObject.toJSONString(msg));
					}else{
						msg.put("type", "pay");
					}
					msg.put("orderType", order.getOrderType());
					if (Long.valueOf(5).equals(order.getOuterSupportId())) {
						msg.put("outOrderNum",
								StringUtils.isEmpty(order.getOutOrderNum()) ? "" : order.getOutOrderNum());
					}
				}
			} else {
				if (msgType == 2) {
					Map<String, String> extras = new HashMap<String, String>();
                    extras.put("type", "order");
                    if (!StringUtils.isEmpty(order.getBuyerMobile())) {
						msg.put("msg", "顾客：" + order.getBuyerMobile() + "，已下单");
					} else {
						if (!StringUtils.isEmpty(order.getBuyNick())) {
							msg.put("msg", "顾客：" + order.getBuyNick() + "，已下单");
						} else {
							msg.put("msg", "顾客已下单");
						}
					}
					// add by ywc 网络订单新增口碑预订单，推送消息需要增加顾客预留手机号，提供云POS打印小票
					msg.put("buyerPhone", StringUtils.isEmpty(order.getBuyerPhone()) ? "" : order.getBuyerPhone());
					msg.put("orderNum", order.getOrderNum());
					msg.put("orderSeq", order.getOrderSeq());
					msg.put("orderType", 0);
					// 预下单
					if (order.getOrderType() != null && new Integer(1).equals(order.getOrderType())) {
						msg.put("type", "alipay-order-hexiao");
						msg.put("identifyingCode", order.getIdentifyingCode());
						extras.put("type", "alipay-order-hexiao");
						extras.put("identifyingCode", order.getIdentifyingCode());
					} else {
						msg.put("type", "alipay-order");
						extras.put("type", "alipay-order");
					}
					// add by ywc 2018年3月17日 外卖订单H5用户支付后消息推送类型，订单推送内容暂时不需要改
					if (Long.valueOf(order.getOuterSupportId()).equals(81L)) {
						msg.put("type", "alipay-order-waimai");
						extras.put("type", "alipay-order-waimai");
					}
					// 极光推送到商家APP
					extras.put("msg", "您有新订单了~");
					extras.put("success", "true");
					extras.put("orderNum", order.getOrderNum());
					JpushUtil.pushMessage4TabletV2("您有新订单了", order.getShopId() + "", extras);
					JpushUtil.pushMessage4APPV2("您有新订单了", order.getShopId() + "", extras);
				} else if (msgType == 3) {
					if (!StringUtils.isEmpty(order.getBuyerMobile())) {
						msg.put("msg", "顾客：" + order.getBuyerMobile() + "，申请退款");
					} else {
						if (!StringUtils.isEmpty(order.getBuyNick())) {
							msg.put("msg", "顾客：" + order.getBuyNick() + "，申请退款");
						} else {
							msg.put("msg", "顾客：申请退款");
						}
					}
					msg.put("orderNum", order.getOrderNum());
					msg.put("orderSeq", order.getOrderSeq());
					msg.put("type", "order-apply-refund");
					// 发送顾客申请退款消息 极光推送到商家APP
					Map<String, String> extras = new HashMap<String, String>();
					extras.put("msg", "顾客申请退款~");
					extras.put("success", "true");
					extras.put("orderNum", order.getOrderNum());
					extras.put("type", "refund");
					JpushUtil.pushMessage4APPAndTablet("顾客申请退款", order.getShopId() + "", extras);
				}
			}
			msg.put("msgCode", msgCode);
			msgObj.put("msg", msg);
			String to = order.getShopId() + "";
			// 配置了秒付数据回流后，推送商家消息至主机
			if (null != hostMachineId) {
				to = to + "_" + hostMachineId;
			} else {
				if (order.getMachineId() != null) {
					to = to + "_" + order.getMachineId();
				}
			}
                logger.error("消息推送：to:" + to + ",msg:" + JSONObject.toJSONString(msg) + ",msgObj:"
					+ JSONObject.toJSONString(msgObj));
			if ((new Integer(0)).equals(aliyunMqtt)) {
				ActiveMqttUtils.sendMsg(to, JSONObject.toJSONString(msg));
			} else {
				AlibabaMQTT.send(to, JSONObject.toJSONString(msg));
			}
			if (msgType < 2) {
				// add by ywc 2018年4月24日 扫码下单的消息，再推送一遍至商家APP H5桌台列表页面
				AlibabaMQTT.send(order.getShopId() + "_shop_h5", JSONObject.toJSONString(msg));

				JSONObject jo = JSONObject.parseObject(JSONObject.toJSONString(msgObj));
				if ("shopper".equals(jo.getString("toUserType"))) {
					String uid = jo.getString("to");
					String machineIdJo = jo.getString("machineId");
					PushType pushType = JpushUtil.PushType.TAG;
					if (!StringUtils.isEmpty(machineIdJo)) {
						uid = uid + "_" + machineIdJo;
						pushType = JpushUtil.PushType.ALIAS;
					}
					JSONObject msgJo = jo.getJSONObject("msg");
					JpushUtil.pushSweepOrderMessage4Tablet(pushType, msgJo.getString("msg"), uid,
							Utils.jsonToMap(msgJo));
					// add by ywc 2017年3月27日 商家APP承接扫码下单，推送消息至商家APP
					// 获取APP承接扫码下单，推送消息至商家APP
					ShopperConfig aPPReceiveSweepOrder = shopperInfoServiceApi.getShopperConfigByShopperId(
							order.getShopId(), Constants.ShopperConfig.CTR_APP_RECEIVE_SWEEPORDER.getValue());
					if (null != aPPReceiveSweepOrder && "1".equals(aPPReceiveSweepOrder.getPropValue())) {
						JpushUtil.pushSweepOrderMessage4ShopperAPP(pushType, msgJo.getString("msg"), uid,
								Utils.jsonToMap(msgJo));
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void sendMsg(SendMsgEntryVO sendMsgEntry) {
		JSONObject jo = sendMsgEntry.getMsg();
		if ("shopper".equals(jo.getString("toUserType"))) {
			String uid = jo.getString("to");
			String machineId = jo.getString("machineId");
			PushType pushType = JpushUtil.PushType.TAG;
			if (!StringUtils.isEmpty(machineId)) {
				uid = uid + "_" + machineId;
				pushType = JpushUtil.PushType.ALIAS;
			}
			JSONObject msgJo = jo.getJSONObject("msg");
			JpushUtil.pushSweepOrderMessage4Tablet(pushType, msgJo.getString("msg"), uid, Utils.jsonToMap(msgJo));
			// update by ywc 2017年4月6日 用户核销推送消息至商家APP
			if ("hexiao".equals(msgJo.getString("type"))) {
				JpushUtil.pushSweepOrderMessage4ShopperAPP(pushType, msgJo.getString("msg"), uid,
						Utils.jsonToMap(msgJo));
			} else {
				ShopperConfig aPPReceiveSweepOrder = shopperInfoServiceApi.getShopperConfigByShopperId(sendMsgEntry.getStoreId(),
						Constants.ShopperConfig.CTR_APP_RECEIVE_SWEEPORDER.getValue());
				if (null != aPPReceiveSweepOrder && "1".equals(aPPReceiveSweepOrder.getPropValue())) {
					JpushUtil.pushSweepOrderMessage4ShopperAPP(pushType, msgJo.getString("msg"), uid,
							Utils.jsonToMap(msgJo));
				}
			}

		}
	}

	@Override
	public MsgRecord saveAddWaimaiMsgRecord(Integer sweepPayPrint, Waimai waimai, DiningArea tableInfo,Long hostMachineId,
			String msgCode) {
		// 开关打开和订单状态是未确认订单和加菜订单会保存，其他的订单不会保存
		if (null==sweepPayPrint || sweepPayPrint==0 || null==waimai || !(waimai.getOrderStatus()==0 || waimai.getOrderStatus()==3)) {
			return null;
		}
		logger.info("订单"+waimai.getOrderNum()+"进入消息保存=================================================");
		MsgRecord msgRecord = new MsgRecord();
		msgRecord.setOrderNum(waimai.getOrderNum());
		String toUrl = waimai.getShopId() + "";
		Long machineId = null;
		// 如果是先付的订单，支付后推送消息到订单中的机器
		if (null!=waimai.getPayStatus() && waimai.getPayStatus()==1) {
			machineId = waimai.getMachineId();
		// 如果是后付的订单，下单后推送到1：主机，2：桌台绑定机器
		} else if ((null==waimai.getOrderStatus() || waimai.getOrderStatus()==0 || waimai.getOrderStatus()==3) && null!=hostMachineId) {
			machineId = hostMachineId;
		} else if ((null==waimai.getOrderStatus() || waimai.getOrderStatus()==0 || waimai.getOrderStatus()==3)) {
			machineId = tableInfo == null ? null : tableInfo.getMachineId();
		}
		if (null!=machineId) {
			toUrl += "_" + machineId;
		}
		msgRecord.setToUrl(toUrl);
		JSONObject msgJson = new JSONObject();
		logger.info("订单"+waimai.getOrderNum()+"保存消息，桌台：" + (null==tableInfo?"null":tableInfo.getName()) + "，主机：" + (null==hostMachineId?"null":hostMachineId));
		// 如果是先付的订单，推送消息内容和类型
		if (null!=waimai.getPayStatus() && waimai.getPayStatus()==1) {
			if(!Utils.isEmpty(waimai.getBuyerMobile())){
				msgJson.put("msg",  "顾客："+waimai.getBuyerMobile()+"，已下单");
			}else{
				if(!Utils.isEmpty(waimai.getBuyNick())){
					msgJson.put("msg",  "顾客："+waimai.getBuyNick()+"，已下单");
				}else{
					msgJson.put("msg",  "顾客已下单");
				}
			}
			msgJson.put("buyerPhone", Utils.isEmpty(waimai.getBuyerPhone())?"":waimai.getBuyerPhone());
			msgJson.put("orderNum", waimai.getOrderNum());
			msgJson.put("orderSeq",  waimai.getOrderSeq());
			msgJson.put("orderType", 0);
			//预下单
			if(waimai.getOrderType()!=null && new Integer(1).equals(waimai.getOrderType())) {
				msgJson.put("type", "alipay-order-hexiao");
				msgJson.put("identifyingCode", waimai.getIdentifyingCode());
			} else {
				msgJson.put("type", "alipay-order");
			}
			if(Long.valueOf(waimai.getOuterSupportId()).equals(81L)){
				msgJson.put("type", "alipay-order-waimai");
			}
		} else {
			// 如果是后付的订单
			if (null!=tableInfo) {
				msgJson.put("tableNo", tableInfo.getName());
				msgJson.put("tableUid", tableInfo.getUid());
				msgJson.put("msg", "桌号：" + tableInfo.getName());
				if (null!=waimai.getOrderStatus() && waimai.getOrderStatus()==3) {
					msgJson.put("msg", msgJson.getString("msg") + "，顾客已加菜");
				} else {
					msgJson.put("msg", msgJson.getString("msg") + "，顾客已下单");
				}
			}
			// 如果是口碑后付的订单
			if (null!=waimai.getOuterSupportId() && new Long(103).equals(waimai.getOuterSupportId())) {
				msgJson.put("type", "koubei-order-notify");
			} else {
				msgJson.put("type", "order");
			}
		}
		msgJson.put("msgCode", msgCode);
		msgRecord.setMsgCode(msgCode);
		msgRecord.setMsg(msgJson.toJSONString());
		msgRecord.setCreateTime(new Date());
		msgRecord.setRepeatTimes(0);
		msgRecord.setMsgType(msgJson.getString("type"));
		msgRecord.setOrderType(waimai.getOrderType());
		msgRecord.setShopId(waimai.getShopperId());
		msgRecord.setStoreId(waimai.getShopId());
		msgRecord.setMachineId(machineId);
		msgRecord.setOuterSupportId(waimai.getOuterSupportId().intValue());
		msgRecord.setOrderDate(waimai.getCreateTime());
		msgRecord.setOrderStatus(waimai.getOrderStatus());
		waimaiServiceApi.saveMsgRecord(msgRecord);
		return msgRecord;
	}

	@Override
	public CoreResponse<StatusInfo> saveMsg(String orderNum, Integer times,Long hostMachineId) {
		CoreResponse<StatusInfo> res = new CoreResponse<StatusInfo>();
		// 1.根据订单号查询订单
		 Waimai waimai = waimaiServiceApi.getWaimaiByOrderNum(orderNum);
		 if(waimai != null ){
			 for (int i = 0; i < times; i++) {
				// logger.info("保存交易记录======count="+count);
		         DiningArea tableInfo = null;
		         if (!Utils.isEmpty(waimai.getTableUid())) {
		             tableInfo = shopperInfoServiceApi.getDiningAreaByUid(waimai.getTableUid());
		         }
				// 2.循环发送消息 并保存消息
				// 3.循环删除消息
		        String msgCode = Utils.createOrderNum(waimai.getShopId()); 
		        webMsgService.sendWebMsg(waimai, (tableInfo == null ? null : tableInfo.getMachineId()), 1,
		                1, hostMachineId,msgCode);
		        
		        // add by ywc 2019年11月27日 	增加下单消息保存
				ShopperConfig sweepPayPrintObj = shopperInfoServiceApi.getShopperConfig(waimai.getShopId(), "CTR_SWEEP_PAY_PRINT");
				Integer sweepPayPrint = sweepPayPrintObj == null ? 0 : Integer.valueOf(sweepPayPrintObj.getPropValue());
				logger.info("开始保存下单消息："+sweepPayPrint);
				webMsgService.saveAddWaimaiMsgRecord(sweepPayPrint, waimai, tableInfo, null, msgCode);
				logger.info("保存下单消息成功：");
			} 
		 }else{
			 res.setStatusInfo(StatusInfo.SUCCESS);
			 res.setMsg("暂无订单");
			 return res;
		 }
		 res.setStatusInfo(StatusInfo.SUCCESS);
		 res.setMsg("循环发送消息成功");
		 return res;
	}

	@Override
	public CoreResponse<StatusInfo> deleteMsg(Integer storeId, Long machineId) {
		CoreResponse<StatusInfo> res = new CoreResponse<StatusInfo>();
		// 1.根据storeId和machineId获取box_msg_record表中的数据，然后循环删除
		List<MsgRecord> list  = waimaiServiceApi.selectMsgRecord(storeId, machineId);
		if(Utils.isEmpty(list)){
			res.setStatusInfo(StatusInfo.SUCCESS);
			res.setMsg("消息都被删除完了没有消息了");
			return res;
		}
		for(MsgRecord msgRecord : list){
			waimaiServiceApi.deleteMsgRecord(msgRecord.getMsgCode());
		}
		res.setStatusInfo(StatusInfo.SUCCESS);
		res.setMsg("消息删除成功");
		return res;
	}

}
